import { defineStore } from 'pinia';

interface NoticeItem {
  title?: string;
  read: boolean;
  message: any;
  time: string;
}

export const useNoticeStore = defineStore('notice', () => {
  const state = reactive({
    notices: [] as NoticeItem[]
  });
  const loadNotices = () => {
    const savedNotices = localStorage.getItem('notices');
    if (savedNotices) {
      state.notices = JSON.parse(savedNotices);
    }else{
      state.notices = []
    }
  };
  const saveNotices = () => {
    const unreadNotices = state.notices.filter((item) => !item.read);
    localStorage.setItem('notices', JSON.stringify(unreadNotices));  // 将未读通知保存到 localStorage
  };
  loadNotices();
  watch(() => state.notices, saveNotices, { deep: true });

  const addNotice = (notice: NoticeItem) => {
    state.notices.push(notice);
  };

  const removeNotice = (notice: NoticeItem) => {
    state.notices.splice(state.notices.indexOf(notice), 1);
  };

  //实现全部已读
  const readAll = () => {
    state.notices.forEach((item: any) => {
      item.read = true;
    });
    state.notices = state.notices.filter((item) => !item.read);
    saveNotices();  // 保存未读消息到 localStorage
  };

  const clearNotice = () => {
    state.notices = [];
    localStorage.removeItem('notices');  // 清除 localStorage 中的消息
  };
  return {
    state,
    addNotice,
    removeNotice,
    readAll,
    clearNotice,
    saveNotices,
  };
});

export default useNoticeStore;
